package com.glorysoft.xztpda.ui.lotcomment

import android.content.Intent
import android.os.Bundle
import com.glorysoft.xztpda.entity.ui.ToastMessageBean
import com.glorysoft.xztpda.BR
import com.glorysoft.xztpda.R
import com.glorysoft.xztpda.base.BaseActivity
import com.glorysoft.xztpda.databinding.ActivityLotCommentBinding
import com.huawei.hms.hmsscankit.ScanUtil
import com.huawei.hms.ml.scan.HmsScan
import kotlinx.android.synthetic.main.activity_lot_comment.*
import kotlinx.android.synthetic.main.activity_lot_comment.etLotID
import kotlinx.android.synthetic.main.activity_lot_comment.ivLotScan
import kotlinx.android.synthetic.main.activity_track_in_guide.*

/**
 * FileName: LotCommentActivity
 * Author: XJH
 * Date: 2022/4/20 11:34
 * Description:
 * History:
 */
class LotCommentActivity : BaseActivity<LotCommentViewModel,ActivityLotCommentBinding>() {
    override fun layoutId(): Int {
        return R.layout.activity_lot_comment
    }

    override fun initVariableId(): Int {
        return BR.lotCommentViewModel
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle("批次备忘登记")
        setRightListener("提交"){
            if (viewModel.lotInfoEntity == null){
                viewModel.defUI.toastEvent.value = ToastMessageBean("请先获取批次信息",false)
                return@setRightListener
            }

            viewModel.putLotComment(etComment.text.toString())
        }

        ivLotScan.setOnClickListener{startScanForCode(this,10001)}
    }

    override fun initData() {
        initEdit(etLotID,object : EditTextListener{
            override fun onTextChangeListener(s: String) {
                viewModel.getLotInfo(s)
            }

        })

        viewModel.defUI.callObserve.observe(this){
            mBinding.lotCommentViewModel = viewModel
        }

        viewModel.defUI.startActivity.observe(this){
            viewModel.defUI.toastEvent.value = ToastMessageBean("操作成功",true)
            finish()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        // 当扫码页面结束后，处理扫码结果。
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK || data == null) {
            return
        }
        if (resultCode == RESULT_OK){
            // 从onActivityResult返回data中，用ScanUtil.RESULT作为key值取到HmsScan返回值。
            when (val obj: Any = data.getParcelableExtra(ScanUtil.RESULT)) {
                is HmsScan -> {
                    val barCode = obj.getOriginalValue()
                    when(requestCode){
                        10001 -> {
                            etLotID.setText(barCode)
                            viewModel.getLotInfo(barCode)
                        }
                    }
                }
            }


        }
    }
}